const axios = require('axios')
const Oumirai = require('./oumirai')
const time = require('./util')
const ak_gacha_table = require('../../../ArknightsGameData/zh_CN/gamedata/excel/gacha_table.json')
const ak_character_table = require('../../../ArknightsGameData/zh_CN/gamedata/excel/character_table.json')
const _ = require('lodash')
const middle = require('./middle')
const config = require('../config/conf')
const fs = require('fs')
const path = require('path')
const gacha_local = require('../../../LocalData/gacha_table.json')
const custom_gacha = require('../../../LocalData/custom_gacha.json')
const custom_character = require('../../../LocalData/custom_character_table.json')
const puppeteer = require('puppeteer')
const { indexOf } = require('lodash')
const { Configuration, OpenAIApi } = require("openai")

let om = null
let akBasicInfo = {
    nickName: "",
    uid: ""
}

function sendUniversalMsg() {
    if (om.msg.includes('医生'))
        return
    om.sendSinlgMessage(om.order.reply)
}

function sendPlainMessage() {
    om.sendSinlgMessage(om.order.reply)
}

function AIDrawing() {
    om.sendGroupMessage(om.sendATGroup(' 图片生成中，请稍等...'))
    let token = ''
    if (!sessionStorage.getItem('accessToken')) {
        console.log('没有可以使用的accessToken')
        om.sendSinlgMessage('ai绘画功能连接失败')
        return
    }
    else {
        token = JSON.parse(sessionStorage.getItem('accessToken'))
    }
    // 分析格式化之后的消息；msgFormat，0：指令，1：style，2：text
    // style支持：古风，油画，水彩画，卡通画，二次元，浮世绘，蒸汽波艺术，像素风格，概念艺术，未来主义，赛博朋克，写实风格，洛丽塔风格，巴洛克风格，超现实主义，
    let styles = ['古风', '油画', '水彩画', '卡通', '二次元', '浮世绘', '蒸汽波艺术', '像素风格', '概念艺术', '未来主义', '赛博朋克', '写实风格', '洛丽塔风格', '巴洛克风格', '超现实主义']
    let text = ''
    if (om.msg.length == 1) {
        om.sendSinlgMessage(om.order.reply)
        return
    }
    else if (om.msg.length >= 2) {
        if (!styles.includes(om.msg[1])) {
            om.sendSinlgMessage('错误的风格词汇，请在以下词汇冲选择想要的风格\n古风，油画，水彩画，卡通，二次元，浮世绘，蒸汽波艺术，像素风格，概念艺术，未来主义，赛博朋克，写实风格，洛丽塔风格，巴洛克风格，超现实主义')
            return
        }
        if (om.msg.length > 2)
            text = om.msg.slice(2).join(' ')
    }

    axios.post('https://wenxin.baidu.com/moduleApi/portal/api/rest/1.0/ernievilg/v1/txt2img', {
        access_token: token,
        text: text,
        style: om.msg[1]
    }).then(res => {
        if (!error(res.data)) return
        let taskId = res.data.data.taskId
        getAIImg(token, taskId)

        // 判断imgUrls字段是否为空来暂停定时器
        let time = setInterval(() => {
            getAIImg(token, taskId, time)
        }, 5000)
    })

}
async function getAIImg(token, taskId, time) {
    axios.post('https://wenxin.baidu.com/moduleApi/portal/api/rest/1.0/ernievilg/v1/getImg', {
        access_token: token,
        taskId: taskId
    }).then(res => {
        if (!error(res.data)) return
        let data = res.data.data
        if (data.imgUrls && data.imgUrls.length > 0) {
            om.sendGroupMessage([...om.sendATGroup(`\n风格：${data.style}\n内容：${data.text}`), ...om.sendGroupImg(data.imgUrls)])
            clearInterval(time)
        }
    })
}

// 文心接口错误状态收集
function error(res) {
    switch (res.code) {
        case 0:
            break
        // 触发屏蔽词
        // case 1:
        //     sendSinlgMessage('不')
        //     return
        case 4001:
            return false
        case 1000001:
            om.sendSinlgMessage('内容不能为空')
            return false
        default:
            om.sendSinlgMessage(res.msg)
            return false
    }
    return true
}

// noveai
async function noveAI() {
    axios.post('http://127.0.0.1:7860/api/predict/', {
        fn_index: 12, data: [`masterpiece,best quality,${om.msg}`, "lowres, bad anatomy, bad hands, text, error, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality, normal quality, jpeg artifacts, signature, watermark, username, blurry", "None", "None", 20, "Euler a", false, false, 1, 1, 7, -1, -1, 0, 0, 0, false, 512, 512, false, false, 0.7, "None", false, false, null, "", "Seed", "", "Steps", "", true, false, null, "", ""], "session_hash": "82zb6qig7by"
    }).then(res => {
        console.log(om.sendGroupImg(res.data.data[0]))
        om.sendGroupMessage([...om.sendATGroup(''), ...om.sendGroupImgBase(res.data.data[0])])
    })
    // om.sendGroupMessage([{
    //     type: "Image",
    //     url: "",
    //     base64: ''
    // }]) 
}

// 百科功能
function baiduBK2img() {
    // let app = document.getElementById('index-main')
    // let tag = '艾雅法拉'
    // // let iframe = `<iframe src="https://baike.baidu.com/item/${tag}" width="100%" frameborder="0" scrolling="no"></iframe>`
    // let page = document.createElement('iframe')
    // page.setAttribute('src', `https://baike.baidu.com/item/${tag}`)
    // page.setAttribute('id', 'page')
    // page.setAttribute('width', '100%')
    // app.appendChild(page)

    // setTimeout(() => {
    //     html2canvas(document.getElementById('page'),{
    //         useCORS: true,
    //         allowTaint: true,
    //     }).then(canvas => {
    //         const src64 = canvas.toDataURL()
    //         console.log('1233333')
    //         console.log(src64)
    //     });
    // }, 5000);
    axios.get('http://localhost:7860').then(res => {
        console.log(res)
    })
}

// 明日方舟-寻访查询功能
function akCardRecord() {
    // 返回结构：{"code":0,"data":{"content":"dBVfq7mnagPob2oazcRaf1Bv"},"msg":""}
    let token = ''
    if (om.msg.length == 1) {
        om.sendSinlgMessage(om.order.reply)
        return
    }
    else if (om.msg.length > 1) {
        om.sendGroupMessage(om.sendATGroup(' 正在查询请稍等...'))
        try {
            token = JSON.parse(om.msg[1]).data.content
        } catch (error) {
            om.sendSinlgMessage('数据错误，请检查复制数据的完整度并重新提交。')
            return
        }
    }
    let basicPostData = token.length < 30 ? {
        appId: 1,
        channelMasterId: 1,
        channelToken: {
            token: token
        }
    } : { token: token }
    // console.log(JSON.stringify(basicPostData) )
    axios({
        method: 'post',
        url: 'https://as.hypergryph.com/u8/user/info/v1/basic',
        data: JSON.stringify(basicPostData),
        headers: { "Content-Type": "application/json; charset=utf-8" }
    }).then(res => {
        // console.log("请求成功输出")
        // console.log(res.data)
        akBasicInfo = res.data.data
    })
        .catch(err => {
            console.log('明日方舟请求个人信息错误输出：')
            console.log(err)
        })
    getGacha(token, token.length < 30 ? 1 : 2)
}

// 卡池内容接口
function getGacha(token, channelId, page = 1, gachas = []) {
    axios({
        method: 'get',
        url: `https://ak.hypergryph.com/user/api/inquiry/gacha`,
        params: {
            page: page,
            token: token,
            channelId: channelId
        }
    })
        .then(res => {

            let data = res.data
            switch (data.code) {
                case 0:
                    gachas = [...gachas, ...data.data.list]
                    if (data.data.pagination.total && Math.ceil(data.data.pagination.total / 10) != page) {
                        getGacha(token, channelId, ++page, gachas)
                    }
                    else {
                        // 发送最后的消息
                        resetGacha(gachas)
                    }
                    break
                default:
                    om.sendSinlgMessage(data.msg || '服务端错误')
                    break
            }
        })
        .catch(err => {
            console.log(err)
            om.sendSinlgMessage('网络错误，请检查是否先登录官网，保证数据中content字段的有效性。')
        })
}

async function resetGacha(list) {
    let total = 0               // 总计
    let chars = []              // 所有出货记录，没有单抽十连区别
    let rarityList = [
        { value: 0, name: '六星', rarity: 5 },
        { value: 0, name: '五星', rarity: 4 },
        { value: 0, name: '四星', rarity: 3 },
        { value: 0, name: '三星', rarity: 2 },
    ]
    let pools = [...new Set(list.map(p => p.pool))]
    let gachaList = pools.map(p => {
        return {
            value: 0,
            name: p,
            acc: 0
        }
    })
    let prizeCount = 0
    let limitPrizeCount = 0
    list.reverse().forEach((item, index) => {
        let gachaItem = gachaList.find(p => p.name == item.pool)
        let akPool = ak_gacha_table.gachaPoolClient.find(p => p.gachaPoolName==item.pool)
        let isLimit = akPool && (akPool.gachaRuleType == 'LIMITED' || akPool.gachaRuleType == 'LINKAGE') ? true : false
        // console.log(akPool)
        chars = [...chars, ...item.chars]
        item.chars.forEach(char => {
            
            gachaItem.acc++
            
            if (isLimit) {
                // char.type = 'LIMITED'
                limitPrizeCount++
                char.count = limitPrizeCount
                if (char.rarity == 5) {
                    gachaItem.acc = 0
                    limitPrizeCount = 0
                }
            }
            else {
                prizeCount++
                char.count = prizeCount
                if (char.rarity == 5) {
                    prizeCount = 0
                    gachaItem.acc = 0
                }
            }
            // if (char.rarity == 5) {
            //     prizeCount = 0
            //     gachaItem.acc = 0
            //     limitPrizeCount = 0
            // }
            let rarityItem = rarityList.find(p => p.rarity == char.rarity)
            rarityItem.value++
            gachaItem.value++
            total++
        })
    })
    rarityList.forEach(item => {
        item.prop = (item.value / total * 100).toFixed(2)
    })
    // 这里需要做图形化处理，效果为向QQ端发送一种记录相关数据的图片
    // 目前能想到的方案为开启一个接口服务，接口路径导向一个html页面，html页面中有echarts的图形化方案，并且开启一个自定义事件监听，监听的便是这里的响应，事件需要向外部输出
    // 以上到自定义事件这里就不可行了，实际上使用的是无头浏览器的方式，在node端直接向html端发送数据和处理dom，所有有关dom的二次渲染和数据交互都在node上完成，所以也不需要处理node和html之间的请求响应。
    // 渲染出错时可以关闭无头模式查看问题
    // const browser = await puppeteer.launch({headless: false})
    const browser = await puppeteer.launch()
    const page = await browser.newPage()
    //设置可视区域大小
    await page.setViewport({ width: 390, height: 844 })
    await page.goto('http://127.0.0.1:8888/index.html', { timeout: 0 })

    // 让页面执行相关的函数
    try {
        await page.evaluate((rarityList, gachaList, total, chars, akBasicInfo) => {
            chart_char.setOption({
                series: [
                    {
                        data: rarityList,
                    }
                ],
            })
            chart_gacha.setOption({
                series: [
                    {
                        data: gachaList,
                    }
                ],
            })
            document.getElementById('user-info').innerHTML = `<p class="text-16-t">Dr.${akBasicInfo.nickName}</p><p class="text-14-g">uid：<span>${akBasicInfo.uid}</span></p>`
            let statisticsInner = ''
            rarityList.forEach(item => statisticsInner = `${statisticsInner}<p>${item.name}共<span>${item.value}</span>个，占<span>${item.prop}</span>%</p>`)
            document.getElementById('statistics').innerHTML = `${statisticsInner}<p style="font-size: 14px;">总计<span style="font-size: 28px; font-weight: 700;">${total}</span>抽</p>`
            let gachaMsgInner = ''
            gachaList.forEach(item => gachaMsgInner = `${gachaMsgInner}<p><span>${item.name}</span>共<span>${item.value}</span>抽，累计<span>${item.acc}</span>抽未出6星</p>`)
            document.getElementById('gacha-msg').innerHTML = gachaMsgInner
            let chars6Inner = ''
            let chars5Inner = ''
            chars.forEach(item => {
                if (item.rarity == 5) {
                    let isNew = item.isNew ? 'display:block;' : 'display:none;'
                    chars6Inner = `${chars6Inner}<div class="chars-tag"><p>${item.name}(${item.count})</p><div class="new" style="${isNew}">new</div><p>、</p></div>`
                }
                else if (item.rarity == 4) {
                    let isNew = item.isNew ? 'display:block;' : 'display:none;'
                    chars5Inner = `${chars5Inner}<div class="chars-tag"><p>${item.name}</p><div class="new" style="${isNew}">new</div><p>、</p></div>`
                }
            })
            document.getElementById('chars6').innerHTML = chars6Inner
            document.getElementById('chars5').innerHTML = chars5Inner
            
        }, rarityList, gachaList, total, chars, akBasicInfo)
    } catch (error) {
        om.sendSinlgMessage('图片生成错误')
        console.log(error)
        return
    }
    
    console.log('DOM处理完毕')
    //对整个页面截图
    const imgBase64 = await page.screenshot({
        type: 'jpeg',
        encoding: "base64",
        fullPage: true,
        quality: 100
    })
    // 截取的图片保存到本地
    // await page.screenshot({
    //     path: './assets/img/capture.png',  //图片保存路径
    //     type: 'png',
    //     fullPage: true //边滚动边截图
    // });
    console.log('图片截取成功')
    await page.close()
    await browser.close()
    console.log('无头浏览器已关闭')
    // 截取到的图片发送到QQ
    om.sendGroupMessage(om.sendGroupImgBase([imgBase64]))


    // 原始方案
    let newList = list.map(p => {
        return `${time.getFullDate(p.ts)} ${p.pool} ${p.chars.map(f => f.name).join('、')}\n`
    })
    // om.sendGroupMessage(om.sendTextMessage(newList))
    // console.log(om.sendForwardMessage([{type: 'Plain', text: newList}]))
    om.sendGroupMessage(
        om.sendForwardMessage(
            om.sendTextMessage(newList)
        )
    )
}

// 明日方舟-阳寿抽卡（寻访模拟）
function akSimulationGacha() {
    // 收到没有参数的指令，/阳寿抽卡
    if (!middle.sessionStores.find(p => p.sessionKey == `${om.group}_${om.qq}_${om.order.orderId}`)) {
        // session组成：指令id，此处的指令id为ak02
        middle.sessionStores.push({
            qq: om.qq,
            sessionKey: `${om.group}_${om.qq}_${om.order.orderId}`,
            guarantee: 0,
            probability: 0.02
        })
    }
    if (om.msg.length == 1) {
        simulationGacha()
        // let gacha = gacha_local.find(p => p.gachaPoolName == config.defaultGacha.gachaPoolName)
        // simulationGachaLocal(gacha)
    }
    else if (om.msg.length >= 2) {
        if (ak_gacha_table.gachaPoolClient.find(p => p.gachaPoolName == om.msg[1])) {
            // 从akdata中获取数据
            let gacha = ak_gacha_table.gachaPoolClient.find(p => p.gachaPoolName == om.msg[1])
            simulationGacha(gacha)
            // 从本地中获取数据
            // let gacha = gacha_local.find(p => p.gachaPoolName == om.msg[1])
            // simulationGachaLocal(gacha)
        }
        else
            om.sendSinlgMessage('未找到卡池')

    }
}

// 自定义卡池抽卡
function ctSimulationGacha() {
    if (!middle.sessionStores.find(p => p.sessionKey == `${om.group}_${om.qq}_${om.order.orderId}`)) {
        // session组成：指令id，此处的指令id为ak02
        middle.sessionStores.push({
            qq: om.qq,
            sessionKey: `${om.group}_${om.qq}_${om.order.orderId}`,
            guarantee: 0,
            probability: 0.02
        })
    }
    if (om.msg.length == 1) {
        if (custom_gacha.find(p => p.gachaPoolId == `CUSTOM_${om.group}`)) {
            let gacha = custom_gacha.find(p => p.gachaPoolId == `CUSTOM_${om.group}`)
            simulationGachaCustom(gacha)
        }

    }
}

// 抽卡接口，默认卡池待完善，期望是跟随游戏进度，优先级：限定>单UP>联合寻访>轮替池
function simulationGacha(gacha = config.defaultGacha) {
    axios({
        method: 'get',
        url: `https://weedy.baka.icu/gacha/${gacha.gachaPoolId}`
    }).then(res => {
        let data = res.data
        switch (data.code) {
            case 0:
                let prizes = []
                let prize = {}
                let store = middle.sessionStores.find(p => p.sessionKey == `${om.group}_${om.qq}_${om.order.orderId}`)
                if (!store || store.sessionKey != `${om.group}_${om.qq}_${om.order.orderId}`) {
                    console.log('没找到相关session')
                    return
                }
                for (let i = 0; i < 10; i++) {
                    prize = ak_character_table[simulationGachaCalc(data.detail, store)]
                    if (prize)
                        prizes.push(prize)
                }
                // 当期up干员
                let upText = data.detail.up.map(p => {
                    return `${p.charIdList.map(p => ak_character_table[p].name).join('、')} ${new Array(p.rarityRank + 1).fill('★').join('')}`
                }).join('，')
                om.sendGroupMessage(
                    om.sendTextMessage([
                        prizes.map(p => `${p.name} ${new Array(p.rarity + 1).fill('★').join('')}`).join('\n'),
                        `\n累计抽卡：${store.guarantee}`,
                        `\n六星出货概率：${store.probability * 100}%\n`,
                        `卡池：${gacha.gachaPoolName}，当期up干员：${upText}`,
                    ])
                )

                // om.sendSinlgMessage(prizes.map(p => `${p.name} ${p.rarity + 1}星`).join('\n'))
                break

            default:
                om.sendSinlgMessage(data.msg || 'weedy访问错误')
                break
        }
    })
        .catch(err => {
            om.sendSinlgMessage('weedy网络错误')
        })
}

// 自定义抽卡数据来源
function simulationGachaCustom(gacha) {
    let prizes = []
    let prize = {}
    let store = middle.sessionStores.find(p => p.sessionKey == `${om.group}_${om.qq}_${om.order.orderId}`)
    if (!store || store.sessionKey != `${om.group}_${om.qq}_${om.order.orderId}`) {
        console.log('没找到相关session')
        return
    }
    for (let i = 0; i < 10; i++) {
        prize = custom_character[simulationGachaCalc(gacha, store)]
        if (prize)
            prizes.push(prize)
    }
    // 当期up干员
    let upText = gacha.up.map(p => {
        return `${p.charIdList.map(p => custom_character[p].name).join('、')} ${new Array(p.rarityRank + 1).fill('★').join('')}`
    }).join('，')
    om.sendGroupMessage(
        om.sendTextMessage([
            prizes.map(p => `${p.name} ${new Array(p.rarity + 1).fill('★').join('')}`).join('\n'),
            `\n累计抽卡：${store.guarantee}`,
            `\n六星出货概率：${store.probability * 100}%\n`,
            `卡池：${gacha.gachaPoolName}，当期up干员：${upText}`,
        ])
    )
}

// 抽卡（调用本地数据，数据来源接口和手动维护，以后有望加入数据库），默认卡池待完善，期望是跟随游戏进度，优先级：限定>单UP>联合寻访>轮替池
function simulationGachaLocal(gacha) {
    let prizes = []
    let prize = {}
    let store = middle.sessionStores.find(p => p.sessionKey == `${om.group}_${om.qq}_${om.order.orderId}`)
    if (!store || store.sessionKey != `${om.group}_${om.qq}_${om.order.orderId}`) {
        console.log('没找到相关session')
        return
    }
    for (let i = 0; i < 10; i++) {
        prize = ak_character_table[simulationGachaCalc(gacha, store)]
        if (prize)
            prizes.push(prize)
    }
    // 当期up干员
    let upText = gacha.up.map(p => {
        return `${p.charIdList.map(p => ak_character_table[p].name).join('、')} ${new Array(p.rarityRank + 1).fill('★').join('')}`
    }).join('，')
    om.sendGroupMessage(
        om.sendTextMessage([
            prizes.map(p => `${p.name} ${new Array(p.rarity + 1).fill('★').join('')}`).join('\n'),
            `\n累计抽卡：${store.guarantee}`,
            `\n六星出货概率：${store.probability * 100}%\n`,
            `卡池：${gacha.gachaPoolName}，当期up干员：${upText}`,
        ])
    )
}


// 抽卡概率计算
function simulationGachaCalc(data, store) {
    // let random = Math.floor(Math.random() * 100)
    let random = Math.random()
    let charIdList = []
    if (store.guarantee > 50) {
        store.probability += 0.02
    }
    let pbAfter3 = 0.4 / 0.98 * (1 - store.probability) + store.probability
    let pbAfter4 = 0.5 / 0.98 * (1 - store.probability) + (0.4 / 0.98 * (1 - store.probability) + store.probability)
    // 六星
    if (random >= 0 && random < store.probability) {
        store.guarantee = 0
        store.probability = 0.02
        let ran = Math.floor(Math.random() * 10)
        let limit = data.limited.length == 0 ? 5 : 7
        if (ran >= 0 && ran < limit) {
            charIdList = data.up.find(p => p.rarityRank == 5).charIdList
        }
        else {
            charIdList = data.ops.find(p => p.rarityRank == 5).charIdList
        }
    }
    // 三星
    else if (random >= store.probability && random < pbAfter3) {
        store.guarantee++
        charIdList = data.ops.find(p => p.rarityRank == 2).charIdList

    }
    // 四星
    else if (random >= pbAfter3 && random < pbAfter4) {
        store.guarantee++
        let pbOps = data.up.find(p => p.rarityRank == 3) ? 8 : 10
        let ran = Math.floor(Math.random() * 10)
        if (ran >= 0 && ran < pbOps) {
            charIdList = data.ops.find(p => p.rarityRank == 3).charIdList
        }
        else {
            charIdList = data.up.find(p => p.rarityRank == 3).charIdList
        }
    }
    // 五星
    else {
        store.guarantee++
        let pbOps = data.up.find(p => p.rarityRank == 4) ? 5 : 10
        let ran = Math.floor(Math.random() * 10)
        if (ran >= 0 && ran < pbOps) {
            charIdList = data.ops.find(p => p.rarityRank == 4).charIdList
        }
        else {
            charIdList = data.up.find(p => p.rarityRank == 4).charIdList
        }
    }
    // 这里应该直接返回抽到的干员ID
    return _.sample(charIdList)
    // let prize = ak_character_table[_.sample(charIdList)]
    // if (prize) {
    //     return {
    //         name: prize.name,
    //         rarity: prize.rarity
    //     }
    // }
    // return { name: '', rarity: 0 }
}

// 来自某位大佬的代码
function input(timeout) {
    return new Promise((resolve) => {
        const dispose = middleware((session) => {
            clearTimeout(timer)
            dispose()
            resolve(content)
        })
        const timer = setTimeout(() => {
            dispose()
            resolve('')
        }, timeout)
    })
}

// 蹲饼
function getAkCookie() {
    let uid = [6279793937, 7499841383]
    for (const item of uid) {
        axios({
            method: 'get',
            url: `https://m.weibo.cn/api/container/getIndex?type=uid&value=${item}&containerid=107603${item}`
        }).then(res => {
            let data = res.data
            if (data.ok == 1 && data.data != null && data.data.cards != null && data.data.cards.length > 0) {
                for (const item of data.data.cards) {
                    let weiboUrl = item.scheme
                    // 过滤转发内容
                    if (item.hasOwnProperty('mblog') && item.mblog.hasOwnProperty('retweeted_status')) {
                        continue
                    }
                    if (item.hasOwnProperty('mblog')) {
                        let mblog = item.mblog
                        // 过滤置顶微博
                        if (item.profile_type_id.indexOf('top') != -1 || (mblog.hasOwnProperty('isTop') && mblog.isTop == 1)) {
                            continue
                        }
                        // 获取最新的饼
                        else {
                            newCookie(mblog, weiboUrl)
                            break
                        }



                    }
                }
            }
            else
                console.log('可能是微博炸了，不关我的事')
        })
    }

}

function newCookie(info, url) {
    // let om = new Oumirai({
    //     order: '',
    //     group: config.cookieGroups,
    //     msgFormat: '',
    //     qq: ''
    // })
    let content = info.raw_text ||
        info.text
            .replace(
                /<a.*?>|<\/a>|<\/span>|<\span.*>|<span class="surl-text">|<span class='url-icon'>|<span class="url-icon">|<img.*?>|全文|网页链接/g,
                ''
            )
            .replace(/<br \/>/g, '\n')
    let img = ''
    let forwardImg = []
    // 是否是视频微博
    if (info.page_info && info.page_info.type == 'video') {
        img = info.page_info.page_pic.url
    }
    // 是否包含图片
    if (info.pics && info.pics instanceof Array && info.pics.length > 0) {
        for (const item of info.pics) {
            forwardImg.push({
                type: 'Image',
                url: item.large.url
            })
        }
        img = forwardImg[0].url
        console.log([img])
    }

    // 群发群消息
    om.sendSinlgMessage(`${content}\n相关链接：${url}`)
    if (img) {
        om.sendGroupMessage(
            om.sendGroupImg([img])
        )
    }
    // 图片多需要发送合并消息
    if (forwardImg.length > 1) {
        om.sendGroupMessage(
            om.sendForwardMessage(forwardImg)
        )
    }
}

// 手动维护卡池，将所有卡池生成新得json
async function maintainGacha() {
    om.sendSinlgMessage(om.order.reply)
    let jsonData = []
    for (const item of ak_gacha_table.gachaPoolClient) {
        simulationGacha2(item, jsonData)
    }
    let dir = path.join(__dirname, '../../../LocalData/gacha_table.json')
    setTimeout(() => {
        fs.writeFile(dir, JSON.stringify(jsonData), 'utf8', (err) => {
            console.log('写入成功')
        })

    }, 60000)

}

// 抽卡接口，默认卡池待完善，期望是跟随游戏进度，优先级：限定>单UP>联合寻访>轮替池
async function simulationGacha2(gacha, jsonData) {
    axios({
        method: 'get',
        url: `https://weedy.baka.icu/gacha/${gacha.gachaPoolId}`
    }).then(res => {
        let data = res.data
        switch (data.code) {
            case 0:
                let newGacha = Object.assign(gacha, JSON.parse(JSON.stringify(data.detail)))
                jsonData.push(newGacha)
                console.log('数据处理中...')
                break

            default:
                om.sendSinlgMessage(data.msg || 'weedy访问错误')
                break
        }
    })
        .catch(err => {
            om.sendSinlgMessage('weedy网络错误')
        })
}

// 新增干员，用于群内专属卡池
function createCharacter() {
    middle.sessions.push({
        session: `${om.group}_${om.qq}`,
        msg: '',
        order: om.order
    })
    om.sendSinlgMessage(om.order.reply)
    setTimeout(() => {
        if (middle.sessions.findIndex(p => p.session == `${om.group}_${om.qq}`) != -1) {
            let index = middle.sessions.findIndex(p => p.session == `${om.group}_${om.qq}`)
            middle.sessions.splice(index, 1)
            om.sendGroupMessage(om.sendATGroup(' 超时，已取消本次修改'))
        }
    }, 60000)
}

// 明日方舟剧情模块
async function akLoadPlot() {

    if (middle.dialogueStorage.find(p => p.group == om.group)) {
        om.sendSinlgMessage('群友正在使用此操作，请稍等...')
        return
    }
    let isAuto = false  // 是否为自动播放
    switch (om.msg.length) {
        case 1:
            om.sendSinlgMessage(om.order.reply)
            return
        case 2:
            break
        case 3:
            if (om.msg[2] == '自动') isAuto = true
            break
        default:
            return
    }
    const AkPlot = require('./akPlot')
    var akPlot = new AkPlot(om.msg[1])
    om.sendSinlgMessage('正在初始化剧情，请稍等...')
    let dialogue = []
    try {
        dialogue = await akPlot.init()
        // console.log(dialogue)
    } catch (error) {
        console.log(error)
        om.sendSinlgMessage('未找到相关剧情。')
        return
    }

    // console.log(dialogue)

    if (dialogue && dialogue instanceof Array && dialogue.length > 0) {

        middle.dialogueStorage.push({
            index: 0,
            group: om.group,
            dialogue: dialogue,
            time: isAuto ? null : setSession(60000, ' 超时！已结束本次操作'),
            isAuto: isAuto
        })
        om.sendSinlgMessage('初始化完成，请输入1进行下一步，输入2结束此次剧情模拟。')
        middle.sessions.push({
            session: `${om.group}_${om.qq}`,
            msg: '',
            order: om.order
        })
        // 清空相关剧情缓存
        // middle.dialogue = []
    }
    else {
        om.sendSinlgMessage('未找到相关剧情。')
    }

}

// openai对话功能
async function openAIChat() {
    const configuration = new Configuration({
        apiKey: config.openaiKey,
    })
    const openai = new OpenAIApi(configuration)
    openai.createCompletion({
        model: "text-davinci-003",
        prompt: "holle",
        temperature: 0,
        max_tokens: 7,
    }).then(res => {
        console.log(res.data)
    }).catch(err => {
        console.log(err)
    })
    // const response = await openai.createCompletion({
    //     model: "text-davinci-003",
    //     prompt: "你好，请用中文回答问题",
    //     temperature: 0,
    //     max_tokens: 7,
    // })
}

function holyPressure() {
    om.sendSinlgMessage(om.order.reply)
    om.sendSinlgMessage('指令识别成功！')
    om.sendSinlgMessage('身份确认中...')
    // if (config.administrator && config.administrator instanceof Array && config.administrator.indexOf(om.qq.toString()) == -1)
    if (config.administrator?.indexOf(om.qq.toString()) == -1) {
        om.sendSinlgMessage('ERROR：身份确认失败，错误代码：403')
        return
    }
    om.sendSinlgMessage(`身份确认成功，您的身份id为：00001，欢迎用户@${om.qq}使用此神罚系统，请输入对其降下神罚的对象QQ号：`)
    middle.sessions.push({
        session: `${om.group}_${om.qq}`,
        msg: '',
        order: om.order
    })
    setSession(60000, ' 超时！已结束本次操作')

}

function setSession(time, msg) {
    return setTimeout(() => {
        if (middle.sessions.findIndex(p => p.session == `${om.group}_${om.qq}`) != -1) {
            let index = middle.sessions.findIndex(p => p.session == `${om.group}_${om.qq}`)
            middle.sessions.splice(index, 1)
            om.sendGroupMessage(om.sendATGroup(msg))
        }
        if (middle.dialogueStorage.findIndex(p => p.group == om.group) != -1) {
            let index = middle.dialogueStorage.findIndex(p => p.group == om.group)
            middle.dialogueStorage.splice(index, 1)
        }
    }, time)
}

// function wsFeature(defaults) {
//     om = new Oumirai(defaults)
//     eval(defaults.order.func + '()')
// }

// module.exports = wsFeature

function wsFeature(defaults) {
    om = new Oumirai(defaults)
    eval(defaults.order.func + '()')
}

function noOrderFeature(defaults) {
    om = new Oumirai(defaults)
    eval('sendUniversalMsg()')
}

module.exports = {
    wsFeature,
    noOrderFeature
}